#!/usr/bin/env python
# -*- coding:utf-8 -*-

import math

from app import db
from models.student_experimentmanagement import t_student_experimentmanagement
from utils import commons
from utils.loggings import loggings
from utils.response_code import RET, error_map_EN


class StudentExperimentmanagementService(object):

    @classmethod
    def joint_query(cls, **kwargs):
    
        page = int(kwargs.get('Page', 1))
        size = int(kwargs.get('Size', 10))

        filter_list = []
    
        if kwargs.get('experiment_id') is not None:
            filter_list.append(t_student_experimentmanagement.columns['experiment_id'] == kwargs.get('experiment_id'))
        if kwargs.get('experiment_name') is not None:
            filter_list.append(t_student_experimentmanagement.columns['experiment_name'] == kwargs.get('experiment_name'))
        if kwargs.get('teacher_id') is not None:
            filter_list.append(t_student_experimentmanagement.columns['teacher_id'] == kwargs.get('teacher_id'))
        if kwargs.get('teacher_name') is not None:
            filter_list.append(t_student_experimentmanagement.columns['teacher_name'] == kwargs.get('teacher_name'))
        if kwargs.get('classroom') is not None:
            filter_list.append(t_student_experimentmanagement.columns['classroom'] == kwargs.get('classroom'))
        if kwargs.get('start_time') is not None:
            filter_list.append(t_student_experimentmanagement.columns['start_time'] == kwargs.get('start_time'))
        if kwargs.get('end_time') is not None:
            filter_list.append(t_student_experimentmanagement.columns['end_time'] == kwargs.get('end_time'))
        if kwargs.get('description') is not None:
            filter_list.append(t_student_experimentmanagement.columns['description'] == kwargs.get('description'))

        try:
            studentexperimentmanagement_info = db.session.query(t_student_experimentmanagement).filter(*filter_list)
            
            count = studentexperimentmanagement_info.count()
            pages = math.ceil(count / size)
            studentexperimentmanagement_info = studentexperimentmanagement_info.limit(size).offset((page - 1) * size).all()
            results = commons.query_to_dict(studentexperimentmanagement_info)

            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages, 'data': results}
    
        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
            
        finally:
            db.session.close()
